package student;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.*;
import java.util.Arrays;

public class TCPServer {
	
	private static final int PORT = 1000;
	
	public static void main(String[] args) throws Exception {
		ServerSocket socket = null;
		try {
			socket = new ServerSocket(PORT);//绑定服务所有IP的端口

			System.out.println("服务器创建完成"+socket.getLocalPort()+socket.getInetAddress());

			while (true){
				//接收一个客户端链接,阻塞的方法，必须要有客户端链接才会执行完成
				Socket client = socket.accept();
				String clientInfo=String.format("客户端[%s:%s]",client.getInetAddress().getHostAddress(),client.getPort());

				Thread t1 =new Thread(()->{
					try {
						InputStream in=client.getInputStream();
						DataInputStream din=new DataInputStream(in);
						String msg=null;
						while (true){
							msg=din.readUTF();
							System.out.println("接收了"+clientInfo+"的消息"+msg);
						}
					}catch (Exception e){
						System.out.println(clientInfo+"接收的消息异常");
					}
				});
				t1.start();

				System.out.format("关闭客户端[%s:%s]",client.getInetAddress().getHostAddress(),client.getPort());
				client.close();//关闭客户端
			}
		} catch (IOException e) {
			e.printStackTrace();
		}finally {

		}
	}

}
